/* RPasswd is a free and GPLed software*/

#include <iostream>
#include <string>

#include <sys/time.h>

#ifdef WINDOWS
#include <windows.h>
#endif

#define DEFAULT_PASSWD_SIZE 8

void print_passwd (int);

int
main (int argc, char *argv[])
{

  if (argc > 1)
   {
      
   int i;
   int passwd_s = 0;
   
    for (i = 0; i < argc; i++)
     {     
      std::string str = argv[i];
      if (str == "--size" || str == "-s")
        if (argv[i+1])
          passwd_s = atoi (argv[i+1]);
     }

    if (passwd_s != 0)
      print_passwd (passwd_s);
    else
      std::cout << "Usage : rpasswd [OPTION]" << std::endl << std::endl
                << "-s, --size [SIZE]   set the password length" << std::endl;

   }
  else
    print_passwd (DEFAULT_PASSWD_SIZE);

  return EXIT_SUCCESS;

}

void
print_passwd (int passwd_size)
{

  int seed;

#ifndef WINDOWS
  timeval tp;
  
  gettimeofday (&tp, NULL);
  seed = tp.tv_usec * tp.tv_sec;
#else
  seed = (int)GetTickCount ();
#endif
  srand (seed);

  std::string table = "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz0123456789_$!";
  std::string passwd;
  int i;
 
  for (i = 0; i < passwd_size; i++)
    passwd += table[(rand () * RAND_MAX) % table.length()];
    
  std::cout << "The random password is : " << passwd << std::endl;

}

